package com.github.yeecode.mybatisdemo.xml;

import java.util.HashMap;
import java.util.Map;

/**
 * org.apache.ibatis.parsing.GenericTokenParser
 *
 * @author : wushikai
 * <p>
 * date : 2021-01-26
 * 占位符解析器
 * 关键就是这个函数 : str.indexOf()  和它的重载 一步步把指针 往后挪;
 */
public class MyGenericTokenParser {

    public static void main(String[] args) {

        String sql = "   SELECT reg_date,merchant_no,merchant_name,expander,belong_branch as vip_dependent,division,father_mer_no as father_merchant_no\n" +
                "   FROM `ftp_vsp_merchant` where 1=1\n" +
                "   and expander like concat(\"%\",#para(username),\"%\");";

        Map<String, String> param = new HashMap<>();
        param.put("username", "林育容");

        if (sql.startsWith("#para")) {


        }
        System.out.println('\\');

        //占位符替换;
        String text = "database:{},username:{}，password:{}";

        //System.out.println(text.indexOf("}", 12));


        System.out.println(parse("{", "}", text, "mysql", "root", "123"));

        //变量名替换;
        HashMap<String, String> map = new HashMap<>();

    }


    /**
     * 第一个占位符 写入 到第二个占位符 写入
     */
    public static String myParse(String openToken, String closeToken, String text, Object... args) {

        int index = 0;
        String complete = "";

        char[] chars = text.toCharArray();

        index = text.indexOf(openToken);
        System.out.println(index);
        complete = text.substring(0, index + 1);

        return null;
    }

    /**
     * 超级简化, 最理想状态;
     * */
    public static String parse(String openToken, String closeToken, String text, Object... params) {

        final char[] src = text.toCharArray();  //转换成字符串数组, 化整为零

        int paramsIndex = 0;  // 传入参数的指针;
        int offset = 0; //流程偏移
        final StringBuilder builder = new StringBuilder(); //构建结果
        int startIndex = text.indexOf(openToken, offset); //开始位置的 指针, 全局中的关键因子


        while (startIndex > -1) {
            System.out.println("startIndex = " + startIndex);
            System.out.println("offset = " + offset);
            builder.append(src, offset, startIndex - offset);
            System.out.println(builder.toString());
            offset = startIndex + 1;
            int end = text.indexOf(closeToken, offset); //往后面找 } 的位置
            String value = params[paramsIndex].toString(); //判都不判, 直接赋值, 把参数写入{} 中
            paramsIndex++;
            builder.append(value);
            offset = end + 1;
            startIndex = text.indexOf(openToken, offset);
        }
        if (offset < src.length) {
            builder.append(src, offset, src.length - offset);
        }
        return builder.toString();
    }
}
